<template>
  <el-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :headers="uploadHeaders"
    :on-success="handleSuccess"
    :action="action"
    :data="uploadData"
    :limit="1"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
import type { UploadProps, UploadUserFile } from 'element-plus'
const requestUrl = import.meta.env.VITE_BASE_URL + '/cert/'
const uploadUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL

// 定义 props
const props = defineProps<{
  deviceId: string | number
  picUrl: string
  modelValue?: string // v-model 的值
  accept?: string // 接受的文件类型
  maxSize?: number // 最大文件大小 (MB)
}>()

// 监听 deviceId 变化
watch(
  () => props.deviceId,
  (newValue, oldValue) => {
    // 当 deviceId 变化时执行相应操作
    console.log('deviceId updated:', newValue)
    // 这里可以触发重新上传或其他逻辑
    uploadData.deviceId = Number(newValue)
  }
)

watch(
  () => props.picUrl,
  (newValue, oldValue) => {
    if (oldValue == '') {
      fileList.value = [
        {
          name: props.picUrl,
          url: requestUrl + newValue
        }
      ]
    }
  }
)

const fileList = ref<UploadUserFile[]>()

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const message = useMessage() // 消息弹窗
const uploadData = reactive({
  deviceId: 0
})
const action = ref('') // 弹窗的标题// 弹窗的标题 uploadUrl + '/upload'
const uploadHeaders = ref() // 上传 Header 头
// 定义 emits
const emits = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'change', file: File | null): void
  (e: 'success', response: any): void
  (e: 'error', error: any): void
}>()

const handleSuccess: UploadProps['onSuccess'] = (response, file) => {
  if (response.code === 0) {
    message.success('上传成功')
    // 替换掉原来的图片
    fileList.value = [
      {
        name: file.name,
        url: requestUrl + response.data
      }
    ]
  } else {
    message.error(response.msg)
  }
  dialogVisible.value = false
  const imageUrl = response.data
  // 更新 v-model 值
  emits('update:modelValue', imageUrl)
  // 触发 success 事件
  emits('success', response)
}

onMounted(() => {
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  action.value = uploadUrl + '/mqtt/device/upload'
})
</script>
